# from django.shortcuts import render
from rest_framework.views import APIView
from .serializers import LoginSerializer,UserSerializer
from datetime import datetime
from rest_framework.response import Response
from rest_framework import status
from .authentications import generate_jwt
# from rest_framework.permissions import IsAuthenticated
from .serializers import ResetPwdSerializer

# Create your views here.
class LoginViews(APIView):
    def post(self,request):
        serialize = LoginSerializer(data=request.data)
        if serialize.is_valid():
            user = serialize.validated_data.get('user')
            user.last_login = datetime.now()
            user.save()
            token = generate_jwt(user)
            return Response({"token": token,"user":UserSerializer(user).data})
        else:
            # {'non_field_errors': [ErrorDetail(string='密码输入错误', code='invalid')]}
            # serialize.errors.values() 获取的是一个dict_values 需要我们把他变成list
            detail = list(serialize.errors.values())[0][0]
            # drf在返回相应是非200的时候 它的错误参数名叫detail  所以我们这里也叫做detail
            return Response({"detail":detail},status=status.HTTP_400_BAD_REQUEST)


# 权限基类
# 方式一  设置视图访问权限的方式  因为大部分接口都需要去设置访问权限 这样过于麻烦
# class AuthenticatedRequiredView:
#     permission_classes = [IsAuthenticated]
#
# class ResetPwdView(APIView,AuthenticatedRequiredView):
#      def post(self,request):
#         return Response({"message": "success"})

# 项目特点 只有登录接口不需要验证是否登录  其他接口都需要验证
class ResetPwdView(APIView):
    # 设置访问这个视图必须登录之后才能使用  我们可以使用中间件
    # permission_classes = [IsAuthenticated]
    def post(self,request):
        # 这个函数的request是rest_framework里面的Request对象 是封装django的HttpRequest对象
        # 将request传过去
        serializer = ResetPwdSerializer(data=request.data,context={'request': request})
        if serializer.is_valid():
            pwd1 = serializer.validated_data.get('pwd1')
            request.user.set_password(pwd1)
            request.user.save()
            return Response({"msg": "修改密码成功"},status=status.HTTP_200_OK)
        else:
            print(serializer.errors)
            detail = list(serializer.errors.values())[0][0]
            return Response({"detail": detail},status=status.HTTP_400_BAD_REQUEST)
        # 这里的request是drf封装的request对象
        #  是针对django request对象进行了封装
        # from rest_framework.request import Request  也就是这里的Request
        # 如果你想获取django 的request对象 可以 request._request
        # return Response({"message": "success"})

